'''
处理实时数据
'''

import requests
import json
import time
import os
from logging import *

from .config import *
from .rainmeter import *

from lib.parse_time import *


def run():
    beaufort_scale = ['无风','软风','轻风','微风','和风','清风','强风','疾风','大风','烈风','狂风','暴风','飓风','台风','强台风I','强台风II','超强台风I','超强台风II','超强台风III']

    basicConfig(
        level=0,
        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
        filename="log",
        filemode="a",
        encoding='UTF-8'
    )

    # read data

    out = Rainmeter()

    target_id = out["ID"]

    # 没钱只能用免费版的了呜呜呜
    try:
        data = requests.get(f"https://devapi.qweather.com/v7/weather/now?key={key}&location={target_id}")
        data = data.content.decode("UTF-8")
        data = json.loads(data)
        data['updateTime'] = reformat(data['updateTime'])
    except requests.ConnectionError:
        error(f"Disconnected from Internet")
        out["warn"] = "获取数据时失败"
        out["warncolor"] = "255,128,128,255"
        info("quit...")
        out.save()
        return
    except KeyError:
        error(f"An Error caused while getting fresh. Detail: {data}")
        out["warn"] = "获取数据时失败"
        out["warncolor"] = "255,128,128,255"
        info("quit...")
        out.save()
        return

    info("Succeed Got Refreshed Data")

    try:
        for k, w in dict(data['now']).items():
            out[k] = w
    except:
        info(f"Error caused while getting fresh. Detail: {data}")
        out["warn"] = "获取数据时失败"
        out["warncolor"] = "255,128,128,255"

    try:
        if out["wind360"] == "-1" or out["wind360"] == "-999":
            out["wind360"] = "~"
        else:
            out["wind360"] += '°'
        out["windScale"] = out["windScale"] + '级 ' + beaufort_scale[int(out["windScale"])]
        out["windSpeed"] += 'km/h'
        out["temp"] += '℃'
        out["humidity"] += '%'
        out["precip"] += 'mm/h'
        out["pressure"] += 'hPa'
        out["vis"] += 'km'

        out["warn"] = f"更新:{data['updateTime']} 天气服务由和风天气驱动"
        out["warncolor"] = "255,255,255,255"
    except:
        ... #TODO

    info("quit...")

